package com.rgc.service.Utiles;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import org.apache.commons.beanutils.BeanUtils;

public class FieldMatchValidator implements
		ConstraintValidator<FieldMatch, Object> {
	private String firstFieldName;
	private String secondFieldName;
	private String errorMessageNAme;
	
	public void initialize(final FieldMatch constraintAnnotation) {
		firstFieldName = constraintAnnotation.first();
		secondFieldName = constraintAnnotation.second();
		errorMessageNAme = constraintAnnotation.message(); 
	}

	@SuppressWarnings("deprecation")
	public boolean isValid(final Object value,
			final ConstraintValidatorContext context) {
		boolean toReturn = false;
		
		try {
			
			
			final Object firstObj = BeanUtils
					.getProperty(value, firstFieldName);
			final Object secondObj = BeanUtils.getProperty(value,
					secondFieldName);
			
			
			toReturn= firstObj == null && secondObj == null || firstObj != null
					&& firstObj.equals(secondObj);
		} catch (final Exception ignore) {
			// ignore
		}
		if(!toReturn) {
			context.disableDefaultConstraintViolation();
			context.buildConstraintViolationWithTemplate(errorMessageNAme).addNode(firstFieldName).addConstraintViolation();
	    }
		return toReturn;
	}
}